package com.stock.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stock.dao.ILoginLogDao;
import com.stock.dao.IUserDao;
import com.stock.entity.LoginLogEntity;
import com.stock.entity.UserEntity;
import com.stock.service.IUserService;
import com.stock.util.JwtUtil;
import com.stock.vo.ResultVo;
import com.stock.vo.UserResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Service
public class UserService extends ServiceImpl<IUserDao, UserEntity> implements IUserService {

    private JwtUtil jwtUtil = new JwtUtil();

    private final IUserDao userDao;
    private final ILoginLogDao loginLogDao;
    private final HttpServletRequest request;

    public UserService(IUserDao userDao, ILoginLogDao loginLogDao, HttpServletRequest request) {
        this.userDao = userDao;
        this.loginLogDao = loginLogDao;
        this.request = request;
    }

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public ResultVo login(UserEntity user) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (ObjectUtil.isNotEmpty(username) && ObjectUtil.isNotEmpty(password)) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username", username);
            queryWrapper.eq("password", password);
            queryWrapper.eq("is_del", 0);
            UserEntity resultEntity = userDao.selectOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(resultEntity)) {
                // 记录一下登录日志
                this.saveLoginLog(resultEntity);
                String token = jwtUtil.generateToken(resultEntity.getUsername());
                UserResultVo resultVo = new UserResultVo();
                resultVo.setUserName(resultEntity.getUsername());
                resultVo.setToken(token);
                resultVo.setPoint(resultEntity.getPoint());
                return ResultVo.success(resultVo);
            } else {
                return ResultVo.error("用户名或密码错误");
            }
        }
        return ResultVo.error("请检查参数");
    }

    /**
     * 保存登录日志
     * @param user
     */
    private void saveLoginLog(UserEntity user) {
        try {
            LoginLogEntity loginLog = new LoginLogEntity();
            loginLog.setUserId(user.getId());
            loginLog.setIp(this.getClientIp());
            loginLog.setLoginTime(new Date());
            loginLogDao.insert(loginLog);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("save login log error:[{}]",e.getMessage(),e);
        }
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public ResultVo register(UserEntity user) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (ObjectUtil.isNotEmpty(username) && ObjectUtil.isNotEmpty(password)) {
            UserEntity resultEntity = this.getUserInfoByUserName(username);
            if (ObjectUtil.isNotEmpty(resultEntity)) {
                return ResultVo.error("用户名已存在");
            } else {
                user.setPoint(7);
                int insert = userDao.insert(user);
                if (insert > 0) {
                    return ResultVo.success("注册成功");
                }
            }
        }
        return ResultVo.error("请检查参数");
    }

    /**
     * 获取ip
     * @return
     */
    private String getClientIp() {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @Override
    public UserEntity getUserInfoByUserName(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        queryWrapper.eq("is_del", 0);
        return userDao.selectOne(queryWrapper);
    }

    /**
     * 获取用户积分
     * @return
     */
    @Override
    public Integer getCurrentUserPoint() {
        // 获取当前认证的用户名
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        UserEntity userEntity = this.getUserInfoByUserName(username);
        return userEntity != null ? userEntity.getPoint() : 0;
    }

}
